require_dependency RAILS_ROOT + '/vendor/plugins/annotations/lib/app/models/annotation'

class Annotation < ActiveRecord::Base
  
  validate :check_category_annotation
  validate :check_example_workflow_url
  
  acts_as_solr(:fields => :value_for_solr)
  
  def test_create(*args)
    Annotation.create(*args)
  end
  
  protected
  
  def value_for_solr
    val = ['']
    
    case self.attribute_name.downcase
      when "category"
        val = [Category.find_by_id(self.value.to_i).try(:name) || ""]
      else
        val = [self.value]
    end
    
    return val
  end
    
  def check_category_annotation
    if self.attribute_name.downcase == "category"
      if Category.find_by_id(self.value).nil?
        self.errors.add_to_base("Please select a valid category")
      end
      return false
    else
      return true
    end
  end 
  
  def check_single_data_format
    if self.attribute_name.downcase == "data_format" && Annotations.find_annotatable(self.annotatable_type, self.annotatable_id)
      self.errors.add_to_base("Only one data format allowed to be specified.")
      return false
    else
      return true
    end
  end
  
  def check_example_workflow_url
    if self.attribute_name.downcase == "example_workflow"
      if self.value =~ /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix
        return true
      else
        self.errors.add_to_base("Please specify a valid workflow URL.")
        return false
      end      
    else
      return true
    end
  end
end
